package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

import Models.POSDiscount;

public class POSDiscountPresenter {
	public ArrayList<POSDiscount> tryJSONParseArray(String input){
		ArrayList<POSDiscount> discounts = new ArrayList<POSDiscount>();
		try{
			JSONObject jsonObj = null;
			jsonObj = XML.toJSONObject(input);
			JSONObject jsonAllObjects = jsonObj.getJSONObject("pOSDiscounts");
				if(!jsonAllObjects.isNull("posDiscount")){
					Object item = jsonAllObjects.get("posDiscount");
					if(item instanceof JSONArray){
						JSONArray jArray = (JSONArray)item;
						for(int i=0; i < jArray.length(); i++){
							JSONObject jObject = jArray.getJSONObject(i);
							discounts.add(createDiscountFromJSONObject(jObject));
						}
					} else {
						JSONObject jObject = (JSONObject)item;
						discounts.add(createDiscountFromJSONObject(jObject));
					}
				}
			return discounts;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public POSDiscount tryJSONParse(String input){
		try{
			JSONObject jsonObj = null;
			jsonObj = XML.toJSONObject(input);
			JSONObject jsonHop = jsonObj.getJSONObject("posDiscount");
			POSDiscount discount = createDiscountFromJSONObject(jsonHop);
			return discount;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public POSDiscount createDiscountFromJSONObject(JSONObject jsonDiscount){
		POSDiscount discount = new POSDiscount();
		try{
			discount.setDescription(jsonDiscount.getString("discountDescription"));
			discount.setFlatRate(jsonDiscount.getDouble("flat"));
			discount.setId(jsonDiscount.getInt("id"));
			discount.setPctRate(jsonDiscount.getDouble("pct"));
			return discount;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(POSDiscount item){
		try{
			JSONObject json = new JSONObject();
			json.put("discountDescription", item.getDescription());
			json.put("id", item.getId());
			json.put("flat", item.getFlatRate());
			json.put("pct", item.getPctRate());
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
}
